The usage of char data[0] in the variable length array struct in C language

  • 2020-05-10 18:34:26
  • OfStack

Today, when I was looking at 1 code, there was a method to use the structure to implement the variable length array. At first, I forgot this technique, so I always felt that the author's source code was wrong. Finally, after deep thinking, I finally remembered the technique to implement the variable length array with struct I had seen before. Here is a very clear article I found online.

In actual programming, we often need to use variable-length arrays, but the C language does not support variable-length arrays. At this point, we can implement variable length arrays in C using struct methods.


struct MyData { int nLen; char data[0];};

In the structure, data is an array name; But that array has no elements; The actual address of the array follows the MyData structure, which is the address of the data behind the structure (if the content assigned to the structure is larger than the actual size of the structure, the rest is the content of data); This declaration is a clever way to extend arrays in the C language.

The actual time is as follows:


struct MyData *p = (struct MyData *)malloc(sizeof(struct MyData )+strlen(str)) 

So you can go through p- > data operates the str.

Program example:


#include <iostream> 
using namespace std; 
struct MyData  
{ 
 int nLen; 
 char data[0]; 
}; 
int main() 
{ 
 int nLen = 10; 
 char str[10] = "123456789"; 
 cout << "Size of MyData: " << sizeof(MyData) << endl; 
 MyData *myData = (MyData*)malloc(sizeof(MyData) + 10); 
 memcpy(myData->data, str, 10); 
 cout << "myData's Data is: " << myData->data << endl; 
 free(myData); 
 return 0; 
}

Output:

Size of MyData: 4

myData"s Data is: 123456789

PS: the pointer must be defined at the end of struct, and the type of the pointer may not be char.


Related articles: